import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class UDPReceiver extends Thread{
	private DatagramSocket serverSocket;
	private UDPConnection udpConnection;
	private byte[] receiveData;
	private boolean continueReceiving;

	public UDPReceiver(DatagramSocket serverSocket, UDPConnection udpConnection){
		this.serverSocket = serverSocket;
		this.udpConnection = udpConnection;
		
	}

	@Override
	public void run(){
		continueReceiving = true;
		while(continueReceiving){
			try{
				receiveData = new byte[Settings.UDPPackageSize];
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				serverSocket.receive(receivePacket);
				String sentence = new String( receivePacket.getData());
				String trimmedData = sentence.trim();
				String[] splitData = trimmedData.split("#");
				if(splitData.length == 3) //[id][packet counter][data]
				{
					int id = Integer.parseInt(splitData[0]); //find id
					long packetCounter = Long.parseLong(splitData[1]);
					String data = splitData[2];
					//System.out.println("Packet # " + packetCounter);

					Client matchingClient = ConnectionHandler.getInstance().getClientById(id); //Find this client

					if(matchingClient != null){ //If client is found
						//If the received data is newer than the previous data
						if(packetCounter > matchingClient.getPlayerData().getUdpPacketCounter()){
							matchingClient.getPlayerData().processUDPData(data);
							matchingClient.getPlayerData().setUdpPacketCounter(packetCounter);
						}
						else System.out.println("Older data received");
					}
					//else System.out.println("Received data from non-existing client! (id: " + id + ")");
				}
			}catch(Exception e){}
		}
	}
	
	/**
	 * Stop receiving
	 */
	public void stopReceiving(){
		try{
			this.continueReceiving = false;
			if(this.serverSocket != null)
				this.serverSocket.close();
			this.serverSocket = null;
		}
		catch(Exception e){System.out.println("Could not close connection in UDPReceiver: " + e);}
	}
}
